#include <header.h>
#include <pthread.h>


pthread_mutex_t mutex;
pthread_cond_t cond;
int flag = 0;

void *fun1(void *){
    int cnt = 2000;
    while(cnt--)
    {
        pthread_mutex_lock(&mutex);
        if(flag == 2)//在这里if和while效果一样
        {
            pthread_cond_wait(&cond,&mutex);
        }
        if(flag == 0)
        {
            printf("A->");
            flag = 1;
        }
        else if(flag == 1)
        {

            printf("B->");
            flag = 2;
        }
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

void *fun2(void *){
    int cnt = 1000;
    while(cnt--)
    {

        pthread_mutex_lock(&mutex);
        if(flag != 2)
        {
            pthread_cond_wait(&cond,&mutex);
        }
        printf("C\n");
        flag  = 0;
        printf("cnt = %d\n",cnt);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);

    }
    return NULL;
}


int main(){


    pthread_mutex_init(&mutex, NULL);
    pthread_t pthid1, pthid2;
    pthread_create(&pthid1, NULL, fun1, NULL);
    pthread_create(&pthid2, NULL, fun2, NULL);

    pthread_join(pthid1, NULL);
    pthread_join(pthid2, NULL);

    pthread_mutex_destroy(&mutex);

    printf("\n");
    return 0;
}

